package com.example.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.entity.Product;
import com.example.entity.ProductHealth;
import com.example.entity.ProductHealthItem;
import com.example.mapper.ProductHealthItemMapper;
import com.example.mapper.ProductHealthMapper;
import com.example.service.IProductHealthItemService;
import com.example.service.IProductHealthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * 商品Service实现类
 */
@Service("productHealthService")
public class IProductHealthServiceImpl extends ServiceImpl<ProductHealthMapper, ProductHealth> implements IProductHealthService {
    @Autowired
    ProductHealthMapper productHealthMapper;
    @Autowired
    ProductHealthItemMapper productHealthItemMapper;

    @Override
    public List<ProductHealth> list(Map<String, Object> map) {
        return productHealthMapper.list(map);
    }

    @Override
    public Long getTotal(Map<String, Object> map) {
        return productHealthMapper.getTotal(map);
    }

    @Override
    public void add(ProductHealth productHealth) {
        productHealthMapper.add(productHealth);
    }

    @Override
    public void update(ProductHealth productHealth) {
        productHealthMapper.update(productHealth);
    }

    @Override
    public ProductHealth findById(Integer id) {
        return productHealthMapper.findById(id);
    }

    @Override
    public void saveProductHealth(ProductHealth productHealth) {
        // 保存 ProductHealth
        if (productHealth.getId() == null || productHealth.getId() == -1) {
            productHealthMapper.add(productHealth);  // 插入新记录，并生成主键 ID
        } else {
            productHealthMapper.update(productHealth); // 更新现有记录
        }

        // 关联保存 ProductHealthItems
        if (productHealth.getProductHealthItems() != null && !productHealth.getProductHealthItems().isEmpty()) {
            // 删除之前的关联项（可选，根据需求决定是否覆盖更新）
            productHealthItemMapper.deleteByHealthId(productHealth.getId());

            // 插入新的关联项
            for (ProductHealthItem item : productHealth.getProductHealthItems()) {
                item.setHealthId(productHealth.getId()); // 绑定 healthId
                productHealthItemMapper.add(item);       // 保存到数据库
            }
        }
    }

}
